class BackTop {
  // 返回顶端的元素
  back = null
  // 定时器的id
  timerId = 0

  // 构造函数
  constructor(back) {
    this.back = document.querySelector(back)
    this.appendUl()
    this.bindScroll()
    this.bindClick()
  }

  // 拼接200个li让页面出现滚动条
  appendUl() {
    let box = this.back.parentNode
    let ul = document.createElement('ul')
    for (let i = 0; i < 200; i++) {
      let li = document.createElement('li')
      li.innerHTML = i + 1
      ul.appendChild(li)
    }
    box.appendChild(ul)
  }

  // 监听窗口的滚动事件
  bindScroll() {
    window.addEventListener(
      'scroll',
      // 使用箭头函数可以让回调函数的this指向BackTop类的实列
      () => {
        // 获得滚动窗口元素
        let html = document.documentElement
        let body = document.body
        // 获得滚动的距离
        let scrollTop = html.scrollTop || body.scrollTop
        // 获得视口高度
        let clientHeight = html.clientHeight || body.clientHeight
        // 监听滚动距离
        if (scrollTop > clientHeight) {
          this.back.style.display = 'block'
        } else {
          this.back.style.display = 'none'
        }
      },
      false
    )
  }

  // 点击返回顶端操作
  bindClick() {
    this.back.addEventListener(
      'click',
      () => {
        if (this.timerId) {
          clearInterval(this.timerId)
        }
        this.timerId = setInterval(() => {
          let top = document.documentElement.scrollTop || document.body.scrollTop
          // 每隔30ms 重新计算speed和top
          let speed = Math.floor(-top / 7)
          // scrollTop会一直变化，变小
          document.documentElement.scrollTop = document.body.scrollTop = top + speed
          if (top === 0) {
            clearInterval(this.timerId)
          }
        }, 30)
      },
      false
    )
  }
}
